<template>
  <!-- wrap-class-name="full-modal" -->
  <div class="parent">
    <a-modal
      :open="isOpen"
      :title="props.editData.ranchId ? '编辑' : '新增'"
      width="1000px"
      style="top: 10px"
      @ok="handleAddEdit"
      @cancel="onCancel"
    >
      <!-- @open="initMap" -->
      <div class="modal-content">
        <div class="left">
          <a-form ref="formRef" :model="addObj" layout="vertical">
            <a-form-item
              label="牧场名称"
              name="ranchName"
              :rules="[
                { required: true, message: '请输入牧场名称' },
                { max: 100, message: '最多输入100个字符' },
              ]"
            >
              <a-input v-model:value="addObj.ranchName"></a-input>
            </a-form-item>

            <a-form-item label="场地规模" name="ranchScale" :rules="ranchScaleRules">
              <a-input v-model:value="addObj.ranchScale" type="number"></a-input>
            </a-form-item>

            <a-form-item label="养殖规模" name="ranchBreed" :rules="ranchBreedRules">
              <a-input v-model:value="addObj.ranchBreed" type="number"></a-input>
            </a-form-item>

            <a-form-item
              label="地址"
              name="ranchAddress"
              :rules="[{ required: true, message: '请选择地址' }]"
              layout="inline"
              style="display: flex"
            >
              <a-cascader
                v-model:value="addObj.ranchAddress"
                :options="options"
                expandTrigger="hover"
                :fieldNames="{ label: 'name', value: 'id', children: 'children' }"
                placeholder="请选择地址"
                style="margin-right: 4px; width: 230px"
                @change="onAddressChange"
              />
            </a-form-item>

            <a-form-item name="ranchAddressDetail" :rules="[{ required: true, message: '请输入详细地址' }]">
              <a-input v-model:value="addObj.ranchAddressDetail" style="width: 234px" placeholder="请输入详细位置" />
            </a-form-item>

            <a-form-item label="位置（经纬度）" name="combinedCoordinates">
              <!-- :rules="[{ required: true, message: '点击地图获取经纬度' }]" -->
              <a-input v-model:value="combinedCoordinates" disabled></a-input>
            </a-form-item>

            <a-form-item label="牲畜品种" name="itemId" :rules="[{ required: true, message: '请选择牲畜品种' }]">
              <a-select v-model:value="addObj.itemId" :options="itemIdOptions" optionLabelProp="label" />
            </a-form-item>
          </a-form>
        </div>
        <div class="right">
          <Map ref="mapRef" :editObj="editObj" :addObj="addObj" @mapSuccess="map"></Map>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, watchEffect, computed, onMounted, onUnmounted, nextTick } from 'vue';
import RanchManage from '@/api/ranch';
import { message } from 'ant-design-vue';
//
import Map from './map.vue';
///
const mapRef = ref(null);
const emits = defineEmits(['cancel', 'success']);
const formRef = ref(null);

const props = defineProps({
  isOpen: {
    type: Boolean,
    required: true,
  },
  editData: {
    type: Object,
  },
});
const addObj = ref({
  ranchName: '',
  ranchScale: null,
  ranchBreed: null,
  ranchAddress: [], // 地址
  ranchAddressDetail: '',
  ranchLatitude: null, // 纬度
  ranchLongitude: null, // 经度
  itemId: null,
  // total: null,
});
// 接收地图参数
const map = (mapData) => {
  // debugger;
  console.log(mapData);
  // 更新 addObj 的经纬度
  addObj.value.ranchLatitude = mapData.ranchLatitude;
  addObj.value.ranchLongitude = mapData.ranchLongitude;
};
//
const combinedCoordinates = computed(() => {
  return `${addObj.value.ranchLatitude}, ${addObj.value.ranchLongitude}`;
});

// 初始化地图
// const initMapAdd = () => {
//   if (props.isOpen) {
//     initMap(); // 确保地图组件有 initMap 方法
//   }
// };
// onMounted(() => {
//   initMap();
//   console.log('初始化地图');
// });
// 清理地图
// const clearMap = () => {
//   clearMap();
// };
// 生命周期钩子
// onBeforeUnmount(() => {
//   clearMap(); // 在组件卸载前清理地图
//   console.log('销毁地图');
// });

// onCancel 事件
const onCancel = () => {
  emits('cancel');
  formRef.value.resetFields();
};

// 获取地址列表
const options = ref([]);
const getAddressList = async () => {
  const res = await RanchManage.getAddress();
  options.value = res.data.data;
};
getAddressList();

// 地址变化处理
const onAddressChange = (value) => {
  const selectedAddresses = value.map((id) => {
    const address = findAddressById(options.value, id);
    return address ? address.name : '';
  });
  addObj.value.ranchAddress = selectedAddresses.join('/');

  // 拼接详细地址
  // const fullAddress = `${addObj.value.ranchAddress} ${addObj.value.ranchAddressDetail}`;

  // 调用地址解析函数，获取经纬度
  // getLocationByAddress(fullAddress);
};

// 根据 ID 查找地址
const findAddressById = (options, id) => {
  for (const option of options) {
    if (option.id === id) {
      return option;
    }
    if (option.children) {
      const found = findAddressById(option.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 增加 修改逻辑
const handleAddEdit = async () => {
  await formRef.value.validateFields();
  const isEdit = !!addObj.value.ranchId;
  if (isEdit) {
    await RanchManage.editRanch({
      ranchId: addObj.value.ranchId,
      ranchName: addObj.value.ranchName,
      ranchScale: addObj.value.ranchScale,
      ranchBreed: addObj.value.ranchBreed,
      ranchAddress: addObj.value.ranchAddress,
      ranchAddressDetail: addObj.value.ranchAddressDetail,
      ranchLatitude: addObj.value.ranchLatitude,
      ranchLongitude: addObj.value.ranchLongitude,
      itemId: addObj.value.itemId,
    });
    message.success('编辑成功');
  } else {
    const res = await RanchManage.addRanch({
      ranchId: addObj.value.ranchId,
      ranchName: addObj.value.ranchName,
      ranchScale: addObj.value.ranchScale,
      ranchBreed: addObj.value.ranchBreed,
      ranchAddress: addObj.value.ranchAddress,
      ranchAddressDetail: addObj.value.ranchAddressDetail,
      ranchLatitude: addObj.value.ranchLatitude,
      ranchLongitude: addObj.value.ranchLongitude,
      itemId: addObj.value.itemId,
    });
    console.log(res);
    message.success('新增成功');
  }
  emits('success');
  formRef.value.resetFields();
};

// 监听 editData 的变化
watchEffect(async () => {
  addObj.value = { ...props.editData };
});
// 定义选项 下拉框获取数据
const itemIdOptions = ref([]);
const getItemList = async () => {
  const res = await RanchManage.getItemList();
  itemIdOptions.value = res.data.data.map((item) => ({
    label: item.itemName,
    value: item.itemId,
  }));
};
getItemList();

// 自定义校验规则
const ranchScaleRules = computed(() => [
  { required: true, message: '请输入场地规模' },
  {
    validator: (_, value) => {
      const numValue = Number(value);
      if (isNaN(numValue) || numValue < 100 || numValue > 9999999) {
        return Promise.reject(new Error('场地规模必须在100到9999999之间'));
      }
      return Promise.resolve();
    },
  },
]);
const ranchBreedRules = computed(() => [
  { required: true, message: '请输入养殖规模' },
  {
    validator: (_, value) => {
      const numValue = Number(value);
      if (isNaN(numValue) || numValue > 999999) {
        return Promise.reject(new Error('养殖规模最大值不超过999999'));
      }
      return Promise.resolve();
    },
  },
]);
//
const editObj = ref({});
watchEffect(() => {
  editObj.value.ranchAddress = addObj.value.ranchAddress;
  editObj.value.ranchAddressDetail = addObj.value.ranchAddressDetail;
});
</script>

<style scoped>
.parent {
  display: flex;
  flex-direction: row;
}

/* 样式代码 */
.modal-content {
  display: flex; /* 使用flex布局 */
}

.left {
  flex: 1; /* 左侧表单占据剩余空间 */
  padding-right: 20px; /* 右侧留出一些空间 */
  max-width: 400px;
}

.right {
  width: 800px; /* 设置地图的宽度 */
  height: 540px; /* 设置地图的高度 */
  background-color: #f0f0f0; /* 可选：设置地图背景颜色 */
  /* border: 2px solid skyblue; */
}

.map {
  width: 100%;
  height: 100%;
  /* 这里可以添加地图的样式 */
}

.full-modal .ant-modal {
  max-width: 100%;
  top: 0;
  padding-bottom: 0;
  margin: 0;
}
#container {
  width: 100%; /*  // 设置地图容器宽度为 100% */
  height: 100%; /*// 设置地图容器高度为 100% */
}
.custom-content-marker {
  text-align: center; /*  // 设置内容居中 */
}
.custom-content-marker img {
  width: 20px; /* // 设置 marker 图标的宽度 */
  height: 20px; /* // 设置 marker 图标的高度 */
}
</style>
